package com.framework.boc.statistics.controller;

import com.framework.boc.response.CommonResponse;
import com.framework.boc.statistics.utils.file.FileUploadUtils;
import com.framework.boc.statistics.utils.file.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/common")
public class CommonController {

    /**
     * 通用下载请求
     *
     * @param filePath 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String filePath, Boolean delete, HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        String[] pathArr = filePath.split("/");
        String fileName = pathArr[pathArr.length - 1];
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
        FileUtils.writeBytes(filePath, response.getOutputStream());
        if (delete) {
            FileUtils.deleteFile(filePath);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    @ResponseBody
    public CommonResponse uploadFile(MultipartFile file) throws Exception {
        // 上传并返回文件路径
        Map<String, String> pathMap = FileUploadUtils.upload(file);
        return CommonResponse.success(pathMap);
    }

}
